package com.miranteinfo.seam.jsf.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Ate que fim uma classe para resolver MIME TYPES
 * 
 * @author lucas lins
 * 
 */
public abstract class MimeTypeUtils {
	
	private static final String MIME_TYPES = "META-INF/mime.types";
	
	private static final Map<String, String> typesMap;
	
	static{
		BufferedReader br = null;
		
		try{
			Map<String, String> map = new HashMap<String, String>();
			
			br = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(MIME_TYPES)));
			String line = null;
			while((line = br.readLine()) != null){
				String[] parts = line.split("\\s+");
		        if (parts.length > 1) {
		        	String type = parts[0];
		        	if(type.startsWith("#")) continue;
		        	for(int i = 1; i < parts.length; i++) map.put(parts[i].toLowerCase(), type);
		        }
			}
			
			typesMap = Collections.unmodifiableMap(map);
		}catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(br != null){
				try{
					br.close();
				}catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		}
	}
	
	public static String getMimeType(String fileName){
		if(fileName == null || fileName.trim().length() == 0) return null;
		int index = 0;
		String extension = (index = fileName.lastIndexOf('.')) < 0 ? fileName : fileName.substring(index + 1, fileName.length());
		return typesMap.get(extension.toLowerCase());
	}
	
}
